package com.adayo.memoryfree.fragment;

import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.view.View;
import android.widget.TextView;

import com.adayo.memoryfree.R;
import com.adayo.memoryfree.activity.AutoStartManageActivity;
import com.adayo.memoryfree.activity.RubbishCleanActivity;
import com.adayo.memoryfree.activity.SoftwareManageActivity;
import com.adayo.memoryfree.base.FragmentBase;
import com.adayo.memoryfree.bean.SDCardInfo;
import com.adayo.memoryfree.utils.AppUtil;
import com.adayo.memoryfree.utils.JLogKit;
import com.adayo.memoryfree.utils.JStorageKit;
import com.adayo.memoryfree.utils.JToastKit;
import com.adayo.memoryfree.widgets.ArcProgress;
import com.jaredrummler.android.processes.AndroidProcesses;
import com.jaredrummler.android.processes.models.AndroidProcess;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@ContentView(R.layout.fragment_main)
public class MainFragment extends FragmentBase {
	@ViewInject(R.id.arc_store)
	ArcProgress arcStore;
	@ViewInject(R.id.arc_process)
	ArcProgress arcProcess;
	@ViewInject(R.id.capacity)
	TextView capacity;
	private Timer timer;
	private Timer timer2;

	@Override
	protected void initWidgets() {
		fillData();
	}

	private void fillData() {
		timer = null;
		timer2 = null;
		timer = new Timer();
		timer2 = new Timer();

		long l = AppUtil.getAvailMemory(context);
		long y = AppUtil.getTotalMemory(context);
		final double x = (((y - l) / (double) y) * 100);

		arcProcess.setProgress(0);
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (arcProcess.getProgress() >= (int) x) {
							timer.cancel();
						} else {
							arcProcess.setProgress(arcProcess.getProgress() + 1);
						}
					}
				});
			}
		}, 50, 20);

		SDCardInfo mSDCardInfo = JStorageKit.getSDCardInfo();
		SDCardInfo mSystemInfo = JStorageKit.getSystemSpaceInfo(context);

		long nAvailaBlock;
		long TotalBlocks;
		if (mSDCardInfo != null) {
			nAvailaBlock = mSDCardInfo.free + mSystemInfo.free;
			TotalBlocks = mSDCardInfo.total + mSystemInfo.total;
		} else {
			nAvailaBlock = mSystemInfo.free;
			TotalBlocks = mSystemInfo.total;
		}

		final double percentStore = (((TotalBlocks - nAvailaBlock) / (double) TotalBlocks) * 100);
		capacity.setText(JStorageKit.convertStorage(TotalBlocks - nAvailaBlock) + "/" + JStorageKit.convertStorage(TotalBlocks));
		arcStore.setProgress(0);

		timer2.schedule(new TimerTask() {
			@Override
			public void run() {
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (arcStore.getProgress() >= (int) percentStore) {
							timer2.cancel();
						} else {
							arcStore.setProgress(arcStore.getProgress() + 1);
						}
					}
				});
			}
		}, 50, 20);
	}

	@Event(value = {R.id.card1, R.id.card2, R.id.card3, R.id.card4, R.id.arc_store,
			R.id.arc_process})
	private void onViewClick(View v) {
		switch (v.getId()) {
			case R.id.arc_process:
			case R.id.card1:
				getTopApp(context);
				//startActivity(MemoryCleanActivity.class, null);
				break;
			case R.id.arc_store:
			case R.id.card2:
				startActivity(RubbishCleanActivity.class, null);
				break;
			case R.id.card3:
				startActivity(AutoStartManageActivity.class, null);
				break;
			case R.id.card4:
				startActivity(SoftwareManageActivity.class, null);
				break;
			default:
				break;
		}
	}

	private void clearMemory(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();
		if (list == null) {
			return;
		}
		for (ActivityManager.RunningAppProcessInfo info : list) {
			String[] pkgList = info.pkgList;
//			if(info.importance >= ActivityManager.
//					RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
			for (int i = 0; i < pkgList.length; i++) {
				JLogKit.getInstance().i("pkg = " + pkgList[i]);
//					if(pkgList[i].equals(context.getPackageName())){
//						continue;
//					}
				am.killBackgroundProcesses(pkgList[i]);
			}
//			}
		}
		String msg = "清理完毕";
		JToastKit.getInstance().showMessage(msg);
	}

	private void getTopApp(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		PackageManager pm = context.getPackageManager();
		List<AndroidProcess> processes = AndroidProcesses.getRunningProcesses();
		JLogKit.getInstance().i("size is : " + processes.size());
		for (AndroidProcess pro : processes) {
			//JLogKit.getInstance().i("pro name is : " + pro.name);
			// 获取应用程序信息
//			try {
//				ApplicationInfo applicationInfo = pm.getApplicationInfo(
//						pro.name, 0);
//				if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
//					// 用户进程
//					JLogKit.getInstance().i("user name is : " + pro.name);
//				} else {
//					// 系统进程
//					JLogKit.getInstance().i("system name is : " + pro.name);
//				}
//			} catch (PackageManager.NameNotFoundException e) {
//				e.printStackTrace();
//			}
		}
		List<ActivityManager.RunningAppProcessInfo> processes1 = AndroidProcesses.getRunningAppProcessInfo(context);
		JLogKit.getInstance().i("size is : " + processes1.size());
		for (ActivityManager.RunningAppProcessInfo info : processes1) {

			// 获取应用程序信息
			try {
				ApplicationInfo applicationInfo = pm.getApplicationInfo(
						info.processName, 0);
				if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
					// 用户进程
					JLogKit.getInstance().i("user name is : " + info.processName);
				} else {
					// 系统进程
					JLogKit.getInstance().i("system name is : " + info.processName);
				}
			} catch (PackageManager.NameNotFoundException e) {
				e.printStackTrace();
			}
		}


		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			UsageStatsManager m = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
			if (m != null) {
				long now = System.currentTimeMillis();
				Calendar beginCal = Calendar.getInstance();
				beginCal.set(Calendar.DATE, 1);
				beginCal.set(Calendar.MONTH, 0);
				beginCal.set(Calendar.YEAR, 2017);
				//获取60秒之内的应用数据
				List<UsageStats> stats = m.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginCal.getTimeInMillis(), now);
				JLogKit.getInstance().i("Running app number in last 60 seconds : " + stats.size());

				String topActivity = "";

				//取得最近运行的一个app，即当前运行的app
				if ((stats != null) && (!stats.isEmpty())) {
					for (UsageStats sta : stats) {
						//JLogKit.getInstance().i("running app is : " + sta.getPackageName());
						am.killBackgroundProcesses(sta.getPackageName());
					}
					int j = 0;
					for (int i = 0; i < stats.size(); i++) {
						if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
							j = i;
						}
					}
					topActivity = stats.get(j).getPackageName();
				}
				JLogKit.getInstance().i("top running app is : " + topActivity);
			}
		}
	}

	@Override
	public void onDestroy() {
		timer.cancel();
		timer2.cancel();
		super.onDestroy();
	}
}
